<template>
  <p>
    <a-space>
      <train-select v-model:trainCode="selectTrainCode" width="200px"></train-select>
      <a-button type="primary" @click="handleQuery">查询</a-button>
      <a-button type="primary" @click="onAdd">新增</a-button>
    </a-space>
  </p>
  <a-table :dataSource="trainStations"
           :columns="columns"
           :pagination="pagination"
           @change="handleTableChange"
           :loading="loading">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a-space>
          <a-popconfirm
              title="删除后不可恢复，确认删除?"
              @confirm="onDelete(record)"
              ok-text="确认" cancel-text="取消">
            <a style="color: red">删除</a>
          </a-popconfirm>
          <a @click="onEdit(record)">编辑</a>
        </a-space>
      </template>
    </template>
  </a-table>
  <a-modal v-model:open="visible" title="火车车站" @ok="handleOk"
           ok-text="确认" cancel-text="取消">
    <a-form :model="trainStation" :label-col="{span: 4}" :wrapper-col="{ span: 20 }">
      <a-form-item label="车次编号">
        <train-select v-model:trainCode="trainStation.trainCode" width="100%"></train-select>
      </a-form-item>
      <a-form-item label="站序">
        <a-input v-model:value="trainStation.index"/>
      </a-form-item>
      <a-form-item label="站名">
        <!--        <a-input v-model:value="trainStation.name"/>-->
        <station-select v-model:stationName="trainStation.name"></station-select>
      </a-form-item>
      <a-form-item label="站名拼音">
        <a-input v-model:value="trainStation.namePinyin"/>
      </a-form-item>
      <a-form-item label="进站时间">
        <a-time-picker v-model:value="trainStation.inTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
      </a-form-item>
      <a-form-item label="出站时间">
        <a-time-picker v-model:value="trainStation.outTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
      </a-form-item>
      <a-form-item label="停站时长">
        <a-time-picker v-model:value="trainStation.stopTime" valueFormat="HH:mm:ss" placeholder="请选择时间" disabled/>
      </a-form-item>
      <a-form-item label="里程（公里）">
        <a-input v-model:value="trainStation.km"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts" name="train-station-view">
import {onMounted, ref, watch} from 'vue';
import {notification} from "ant-design-vue";
import {deleteById, query, save} from "@/api/base/train-station";
import {copyObj, isNotEmpty, getStrPinyin} from "@/utils/tools.ts";
import TrainSelect from "@/components/train-select.vue";
import StationSelect from "@/components/station-select.vue";
//@ts-ignore
import dayjs from "dayjs";


const visible = ref(false);
let trainStation = ref<SaveParams>({
  id: undefined,
  inTime: "",
  index: "",
  km: 0,
  name: "",
  namePinyin: "",
  outTime: "",
  stopTime: "",
  trainCode: "",
  createTime: undefined,
  updateTime: undefined
});

const selectTrainCode = ref<string|undefined>(undefined);

const trainStations = ref([]);

// 分页的三个属性名是固定的
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 15,
});
let loading = ref(false);
const columns = [
  {
    title: '车次编号',
    dataIndex: 'trainCode',
    key: 'trainCode',
  },
  {
    title: '站序',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '站名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '站名拼音',
    dataIndex: 'namePinyin',
    key: 'namePinyin',
  },
  {
    title: '进站时间',
    dataIndex: 'inTime',
    key: 'inTime',
  },
  {
    title: '出站时间',
    dataIndex: 'outTime',
    key: 'outTime',
  },
  {
    title: '停站时长',
    dataIndex: 'stopTime',
    key: 'stopTime',
  },
  {
    title: '里程（公里）',
    dataIndex: 'km',
    key: 'km',
  },
  {
    title: '操作',
    dataIndex: 'operation'
  }
];
watch(()=>trainStation.value.inTime,() => {
  let diff = dayjs(trainStation.value.outTime,"HH:mm:ss").diff(dayjs(trainStation.value.inTime,"HH:mm:ss"),"seconds");
  trainStation.value.stopTime = dayjs("00:00:00","HH:mm:ss").second(diff).format("HH:mm:ss");


},{immediate:true})

watch(()=>trainStation.value.outTime,() => {
  let diff = dayjs(trainStation.value.outTime,"HH:mm:ss").diff(dayjs(trainStation.value.inTime,"HH:mm:ss"),"seconds");
  trainStation.value.stopTime = dayjs("00:00:00","HH:mm:ss").second(diff).format("HH:mm:ss");
},{immediate:true})

const onAdd = () => {
  trainStation.value = {
    createTime: undefined,
    id: undefined,
    inTime: undefined,
    index: "",
    km: 0,
    name: "",
    namePinyin: "",
    outTime: undefined,
    stopTime: undefined,
    trainCode: "",
    updateTime: undefined
  };
  visible.value = true;
};

const onEdit = (record: any) => {
  trainStation.value = copyObj(record);
  visible.value = true;
};

watch(() => trainStation.value.name, (value) => {
  if (isNotEmpty(value)) {
    trainStation.value.namePinyin = getStrPinyin(value)
  }
})

const onDelete = async (record: any) => {
  try {
    const result = await deleteById(record.id as number);
    if (result.success) {
      notification.success({message: "操作成功！", description: "删除成功！"});
      await handleQuery({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize,
      });
    } else {
      notification.error({message: undefined, description: result.message});
    }
  } catch (e: any) {
    notification.error({message: undefined, description: e.message});
  }
};

const handleOk = async () => {
  try {
    const result = await save(trainStation.value);
    if (result.success) {
      notification.success({message: "操作成功!", description: "保存成功！"});
      visible.value = false;
      await handleQuery({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize
      });
    } else {
      notification.error({message: "失败", description: result.message});
    }
  } catch (e: any) {
    notification.error({message: "失败", description: e.message});
  }
};

const handleQuery = async (param: any) => {
  if (!param) {
    param = {
      pageNum: 1,
      pageSize: pagination.value.pageSize
    };
  }
  loading.value = true;
  try {
    const result = await query({...param, trainCode: selectTrainCode.value});
    loading.value = false;
    if (result.success) {
      trainStations.value = result.data as any;
      // 设置分页控件的值
      pagination.value.current = param.pageNum as number;
      pagination.value.total = result.total;
    } else {
      notification.error({message: "失败", description: result.message});
    }
  } catch (e: any) {
    notification.error({message: "失败", description: e.message});
  }
};

const handleTableChange = (page: any) => {
  // console.log("看看自带的分页参数都有啥：" + JSON.stringify(page));
  pagination.value.pageSize = page.pageSize;
  handleQuery({
    pageNum: page.current,
    pageSize: page.pageSize
  });
};

onMounted(() => {
  handleQuery({
    pageNum: 1,
    pageSize: pagination.value.pageSize
  });
})
</script>
